package de.bloxel.world;

import java.io.IOException;

import com.jme3.bounding.BoundingBox;
import com.jme3.collision.Collidable;
import com.jme3.collision.CollisionResults;
import com.jme3.export.InputCapsule;
import com.jme3.export.JmeExporter;
import com.jme3.export.JmeImporter;
import com.jme3.export.OutputCapsule;
import com.jme3.export.Savable;
import com.jme3.math.Vector3f;

import de.bloxel.core.BloxelFactory.BloxelType;

/**
 * @author andreas
 * @since 0.1.0
 */
public class TerrainElement implements Savable {

  private BoundingBox boundingBox;
  private BloxelType bloxelType;
  private Vector3f dimension;
  private boolean removeable = true;
  private boolean inPhysicalSpacePresent;

  public TerrainElement(final Vector3f center, final Vector3f theDimension, final BloxelType type) {
    this(center, theDimension, type, true, true);
  }

  public TerrainElement(final Vector3f center, final Vector3f theDimension, final BloxelType type,
      final boolean isRemoveable, final boolean theIsInPhysicalSpacePresent) {
    dimension = theDimension;
    bloxelType = type;
    inPhysicalSpacePresent = theIsInPhysicalSpacePresent;
    boundingBox = new BoundingBox(center, theDimension.x, theDimension.y, theDimension.z);
    removeable = isRemoveable;
  }

  public void collideWith(final Collidable aCollidable, final CollisionResults results) {
    boundingBox.collideWith(aCollidable, results);
  }

  public BloxelType getBloxelType() {
    return bloxelType;
  }

  public Vector3f getCenter() {
    return boundingBox.getCenter();
  }

  public Vector3f getDimension() {
    return dimension;
  }

  public boolean isInPhysicalSpacePresent() {
    return inPhysicalSpacePresent;
  }

  public boolean isRemoveable() {
    return removeable;
  }

  @Override
  public void read(final JmeImporter im) throws IOException {
    final InputCapsule ic = im.getCapsule(this);
    bloxelType = ic.readEnum("bloxelType", BloxelType.class, BloxelType.POND);
    boundingBox = (BoundingBox) ic.readSavable("boundingBox", null);
    dimension = (Vector3f) ic.readSavable("dimension", Vector3f.UNIT_XYZ);
  }

  public void setInPhysicalSpacePresent(final boolean theInPhysicalSpacePresent) {
    inPhysicalSpacePresent = theInPhysicalSpacePresent;
  }

  @Override
  public String toString() {
    return String.format("bb: %s, dim: %s", boundingBox, dimension);
  }

  @Override
  public void write(final JmeExporter ex) throws IOException {
    final OutputCapsule oc = ex.getCapsule(this);
    oc.write(bloxelType, "bloxelType", null);
    oc.write(boundingBox, "boundingBox", null);
    oc.write(dimension, "dimension", Vector3f.UNIT_XYZ);
  }
}
